//
//  PlayViewController.m
//  练习11
//
//  Created by 张琦 on 15/11/23.
//  Copyright © 2015年 张琦. All rights reserved.
//

#import "PlayViewController.h"
#import "MusicPlay.h"
#import "ViewPlayer.h"

#define SCR_WIDTH     [UIScreen mainScreen].bounds.size.width
#define SCR_HEIGHT    [UIScreen mainScreen].bounds.size.height

@interface PlayViewController ()<MyMusicPlayDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIButton *buttonPlay;
@property (nonatomic, retain) UIButton *buttonUp;
@property (nonatomic, retain) UIButton *buttonNext;
@property (nonatomic, retain) UIButton *buttonPlayPattern; // 播放模式
@property (nonatomic, retain) UISlider *slider;
@property (nonatomic, retain) UIView *viewPlay;

@property (nonatomic, retain) UILabel *labelBegin;
@property (nonatomic, retain) UILabel *labelEnd;

@end

@implementation PlayViewController

- (void)dealloc
{
    [_buttonNext release];
    [_buttonPlay release];
    [_buttonUp release];
    [_viewPlay release];
    [_labelEnd release];
    [_slider release];
    [super dealloc];
}

+ (instancetype)sharePlayViewController
{
    static PlayViewController *play = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        play = [[PlayViewController alloc] init];
    });
    return play;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleButtonChange:) name:@"buttonChange" object:nil];
    }
    return self;
}



- (void)handleButtonChange:(NSNotification *)noti
{
    if ([[noti.userInfo objectForKey:@"play"] isEqualToString:@"YES"]) {
        self.buttonPlay.selected = NO;
    } else {
        self.buttonPlay.selected = YES;
    }
}

- (void)createViewPlayer
{
    self.viewPlay = [[UIView alloc] initWithFrame:CGRectMake(0, SCR_HEIGHT - 150 - 64, SCR_WIDTH, 150)];
    self.viewPlay.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.viewPlay];
    [_viewPlay release];
    
    self.buttonUp = [UIButton buttonWithType:UIButtonTypeCustom];
    //    self.buttonUp.backgroundColor = [UIColor cyanColor];
    [self.viewPlay addSubview:self.buttonUp];
    
    self.buttonPlay = [UIButton buttonWithType:UIButtonTypeCustom];
    //    self.buttonPlay.backgroundColor = [UIColor cyanColor];
    [self.viewPlay addSubview:self.buttonPlay];
    
    self.buttonNext = [UIButton buttonWithType:UIButtonTypeCustom];
    //    self.buttonNext.backgroundColor = [UIColor cyanColor];
    [self.viewPlay addSubview:self.buttonNext];
    
    self.buttonUp.frame = CGRectMake(60, 50, 50, 50);
    self.buttonPlay.frame = CGRectMake(140, 30, 80, 80);
    self.buttonNext.frame = CGRectMake(250, 50, 50, 50);
    
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(20, 10, SCR_WIDTH - 40, 10)];
    //    self.slider.backgroundColor = [UIColor cyanColor];
    [self.viewPlay addSubview:self.slider];
    [_slider release];
    
    self.labelBegin = [[UILabel alloc] initWithFrame:CGRectMake(30, 20, 60, 30)];
    self.labelBegin.text = @"--:--";
    self.labelBegin.textColor = [UIColor whiteColor];
    [self.viewPlay addSubview:self.labelBegin];
    [_labelBegin release];
    
    self.labelEnd = [[UILabel alloc] initWithFrame:CGRectMake(300, 20, 60, 30)];
//    self.labelEnd.backgroundColor = [UIColor cyanColor];w
    self.labelEnd.text = @"--:--";
    self.labelEnd.textColor = [UIColor whiteColor];
    [self.viewPlay addSubview:self.labelEnd];
    [_labelEnd release];
    
    // 添加按钮点击事件
    [self.buttonUp addTarget:self action:@selector(buttonPlayUp:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonPlay addTarget:self action:@selector(buttonPlaySong:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonNext addTarget:self action:@selector(buttonPlayNext:) forControlEvents:UIControlEventTouchUpInside];
    [self.slider addTarget:self action:@selector(handleSlider:) forControlEvents:UIControlEventValueChanged];
    
    // 设置buttonPlay
    [self.buttonPlay setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang1"] forState:UIControlStateNormal];
    [self.buttonPlay setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang"] forState:UIControlStateSelected];
    self.buttonPlay.layer.masksToBounds = YES;
    self.buttonPlay.layer.cornerRadius = 40;
    
    [self.buttonUp setBackgroundImage:[UIImage imageNamed:@"iconfont-shangyishou"] forState:UIControlStateNormal];
    self.buttonUp.layer.masksToBounds = YES;
    self.buttonUp.layer.cornerRadius = 25;
    
    [self.buttonNext setBackgroundImage:[UIImage imageNamed:@"iconfont-xiayishou"] forState:UIControlStateNormal];
    self.buttonNext.layer.masksToBounds = YES;
    self.buttonNext.layer.cornerRadius = 25;
    
    
    // 设置slidr的初始值
    self.slider.minimumValue = 0;
    self.slider.maximumValue = 1;
    [self.slider setThumbImage:[UIImage imageNamed:@"iconfont-icoyuan"] forState:UIControlStateNormal];

    [MusicPlay shareMusicPlay].delegate = [PlayViewController sharePlayViewController];
    
    [self judgeData];
}
#pragma mark 是否有数据
- (void)judgeData
{
    if (self.array) {
        [MusicPlay shareMusicPlay].urlStr = [self getURL:self.currentNumber];
        [[MusicPlay shareMusicPlay] playSong];
    } else {
        return;
    }
    // 先判断是否正在播放歌曲
    if (![MusicPlay shareMusicPlay].urlStr) {
        self.buttonPlay.selected = YES;
    } else {
        self.buttonPlay.selected = NO;
    }

}

// 播放结束之后去播放下一首歌曲
- (void)musicPlayFinished
{
    [self buttonPlayNext:self.buttonNext];  // 播放下一首
}

// 得到歌曲的总进度
- (void)musicPlayWithProgress:(float)progress during:(float)during
{
//    NSLog(@"%lf", progress);
    self.slider.minimumValue = 0;
    self.slider.maximumValue = (int)during;

    self.slider.value = progress;
    self.labelBegin.text = [self timeOfChange:progress];
    self.labelEnd.text = [self timeOfChange:self.slider.maximumValue];
}
// 时间格式化
- (NSString *)timeOfChange:(float)time
{
    int minent = time / 60;
    int section = (int)time % 60;
    NSString *str = [NSString stringWithFormat:@"%d:%02d", minent, section];
    return str;
}
#pragma mark - 滑块事件
- (void)handleSlider:(UISlider *)slider
{
//    [[MusicPlay shareMusicPlay] pauseSong];
    // 先暂停歌曲
    [[MusicPlay shareMusicPlay] sliderToTimer:slider.value];
}
#pragma mark - 播放上一首
- (void)buttonPlayUp:(UIButton *)button
{
    if (self.currentNumber == 0) {
        self.currentNumber = self.array.count - 1;
    } else {
        self.currentNumber--;
    }
    
    // 播放
    [MusicPlay shareMusicPlay].urlStr = [self getURL:self.currentNumber];
    // 通知播放的View区改变
    NSDictionary *dic = [self.array objectAtIndex:self.currentNumber];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ViewChange" object:nil userInfo:@{@"name":[dic objectForKey:@"name"]}];
}
#pragma mark - 播放
- (void)buttonPlaySong:(UIButton *)button
{
    self.buttonPlay.selected = !self.buttonPlay.selected;
    if (button.selected) {         //暂停
        [[MusicPlay shareMusicPlay] pauseSong];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ViewStopOrPlay" object:nil userInfo:@{@"play":@"NO"}];
    } else {
        [[MusicPlay shareMusicPlay] playSong];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ViewStopOrPlay" object:nil userInfo:@{@"play":@"YES"}];
    }
}
#pragma mark - 播放下一首
- (void)buttonPlayNext:(UIButton *)button
{
    if (self.currentNumber == self.array.count - 1) {
        self.currentNumber = 0;
    } else {
        self.currentNumber++;
    }
    // 播放
    [MusicPlay shareMusicPlay].urlStr = [self getURL:self.currentNumber];
    self.slider.maximumValue = (int)[MusicPlay shareMusicPlay].during;
    self.labelEnd.text = @"";
    self.labelEnd.text = [NSString stringWithFormat:@"%lf", self.slider.maximumValue];
    
    
    // 通知播放的View改变
    NSDictionary *dic = [self.array objectAtIndex:self.currentNumber];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ViewChange" object:nil userInfo:@{@"name":[dic objectForKey:@"name"]}];
}

// 取得要播放的URL
- (NSString *)getURL:(NSInteger)number
{
    NSDictionary *dic = [self.array objectAtIndex:self.currentNumber];
    NSDictionary *dicList = [[dic objectForKey:@"auditionList"] firstObject];
   return [dicList objectForKey:@"url"];

}

// 视图将要出现和消失的时候去管理ViewPlayer
- (void)viewWillAppear:(BOOL)animated
{
    [ViewPlayer shareViewPlayer].hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [ViewPlayer shareViewPlayer].hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self createViewPlayer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
